﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Configuration;

namespace AE_TimeSheet_EmailNotification
{
    public class SendEmail
    {
        #region Objects

        MailMessage myMailMessage;
        string sFromMailId = ConfigurationManager.AppSettings["FromMailId"];
        string sFromMailIdPassword = ConfigurationManager.AppSettings["FromMailIdPassword"];
        string sSMTPHost = ConfigurationManager.AppSettings["SMTPHost"];
        int iSMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);
        int iSMTPConnTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPConnTimeout"]);

        #endregion

        #region Methods

        public string SendAutomatedEmail(DataSet ds)
        {
            string sstrSent = "";
            string sFuncName = string.Empty;
            string sErrorDesc = string.Empty;
            Int16 DEBUG_ON = 1;
            Int16 DEBUG_OFF = 0;
            Int16 p_iDebugMode = DEBUG_ON;
            clsLog oLog = new clsLog();
            try
            {
                sFuncName = "SendAutomatedEmail";
                if (p_iDebugMode == DEBUG_ON) oLog.WriteToDebugLogFile("Starting Function ", sFuncName);
                Console.WriteLine("Starting Function " + sFuncName);
                if (ds != null && ds.Tables.Count > 0)
                {
                    var result = from r in ds.Tables[0].AsEnumerable()
                                 group r by new { Group = r["ConsultantEmailId"], StartDate = r["FormattedStartDate"] } into g
                                 select new { Group = g.Key.Group, StartDate = g.Key.StartDate };

                    foreach (var item in result)
                    {
                        if (p_iDebugMode == DEBUG_ON) oLog.WriteToDebugLogFile("Composing the content for Email Id '" + item.Group + "'", sFuncName);
                        Console.WriteLine("Composing the content for Email Id '" + item.Group + "'");
                        myMailMessage = new MailMessage();

                        DataRow[] dr = ds.Tables[0].Select("ConsultantEmailId = '" + item.Group + "'");
                        if (dr.Length > 0)
                        {
                            DataTable dtFilter = dr.CopyToDataTable();
                            myMailMessage.IsBodyHtml = true;
                            myMailMessage.Body = ComposeBody(dtFilter);

                            var filter = from r in dtFilter.AsEnumerable() group r by new { Group = r["ProjMgrEmailId"] } into g select new { Group = g.Key.Group };

                            foreach (var ProjMgrId in filter)
                            {
                                if (ProjMgrId.Group.ToString().Length > 0)
                                {
                                    myMailMessage.CC.Add(new MailAddress(ProjMgrId.Group.ToString()));
                                }
                            }

                        }
                        myMailMessage.From = new MailAddress(sFromMailId);
                        myMailMessage.To.Add(new MailAddress(item.Group.ToString()));
                        myMailMessage.Subject = "Timesheet Entry Reminder for the week of " + item.StartDate + ".";

                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = sSMTPHost;
                        smtp.Port = iSMTPPort;
                        smtp.Timeout = iSMTPConnTimeout;
                        smtp.Credentials = new NetworkCredential(sFromMailId, sFromMailIdPassword);
                        smtp.EnableSsl = true;

                        Console.WriteLine("Before sending Mail to '" + item.Group + "'");
                        if (p_iDebugMode == DEBUG_ON) oLog.WriteToDebugLogFile("Before sending Mail to '" + item.Group + "'", sFuncName);
                        smtp.Send(myMailMessage);
                        //sstrSent = "Email Sent Successfully";
                        if (p_iDebugMode == DEBUG_ON) oLog.WriteToDebugLogFile("After sending Mail to '" + item.Group + "'", sFuncName);
                        Console.WriteLine("After sending Mail to '" + item.Group + "'");
                        Console.WriteLine("Email Sent Successfully...");
                    }
                }
            }
            catch (Exception ex)
            {
                sstrSent = (ex.InnerException).InnerException.ToString();
                if (p_iDebugMode == DEBUG_ON) oLog.WriteToErrorLogFile(sstrSent, sFuncName);
                if (p_iDebugMode == DEBUG_ON) oLog.WriteToErrorLogFile("Completed with error ", sFuncName);
                return sstrSent;
            }
            return sstrSent;
        }

        public string ComposeBody(DataTable dtBody)
        {
            string sBodyDetail = string.Empty;
            string sBodyDetail1 = string.Empty;
            string sTableFormat = string.Empty;
            decimal dtotalHours = 0;
            foreach (DataRow item in dtBody.Rows)
            {
                sBodyDetail = "<tr><td> &nbsp;" + item["KeyInDate"] + "</td><td>&nbsp;" + item["KeyInProjName"].ToString() +
                                " </td><td>&nbsp;" + item["TotalHours"].ToString() + " </td></tr>";
                sBodyDetail1 = sBodyDetail1 + sBodyDetail;
            }
            dtotalHours = (decimal)dtBody.Compute("Sum(TotalHours)", "");
            if (dtotalHours > 0)
            {
                sTableFormat = "<table border = '1' cellspacing = 0 cellpadding = 0 style='font-size:10.0pt;font-family:Arial;width: 85%;'> " +
                                    "<tr><td><strong style='color: blue; background-color: transparent;'>&nbsp;Date&nbsp;</strong></td> " +
                                    "<td><strong style='color: blue; background-color: transparent;'>&nbsp;Project &nbsp; </strong></td> " +
                                    "<td><strong style='color: blue; background-color: transparent;'>&nbsp;Hours &nbsp;</strong></td></tr> " +
                                    sBodyDetail1 + " <tr><td colspan = '2'><strong style='color: blue; background-color: transparent;'> &nbsp;Total Hours &nbsp; </strong></td><td><strong style='color: blue; background-color: transparent;'>  &nbsp;" + dtotalHours + "  &nbsp;</strong></td></tr> </table> ";
            }
            else
            {
                sTableFormat = "<strong style='color: blue; background-color: transparent;'> Total Hours is 0 </strong> <br/>";
            }
            string stextBody = "<p style='font-size:10.0pt;font-family:Arial;'>Dear <strong>" + dtBody.Rows[0]["ConsultantName"].ToString() + ",</strong><br /><br /> You have not entered a minimum of 40 hours " +
                                "for the week of " + dtBody.Rows[0]["FormattedStartDate"].ToString() +
                                ".<br/><br /> Timesheet entry for the week of " + dtBody.Rows[0]["FormattedStartDate"].ToString() + " : <br/>" +
                                sTableFormat + "<br/> Timesheet URL : http://timesheet.abeo-electra.com <br/>" +
                                " <br/><br/> Regards,<br/> Admin.<br/><br/> *** (This is a system generated e-mail and please do not reply) ***</p>";

            return stextBody;
        }

        #endregion
    }
}
